package srdb.migration.script;

import java.io.File;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

public class ScriptUtil {
	public static String getArg(String args[], String key) {
		for (int i = 0; i < args.length; i++) {
			String key_temp = StringUtils.substringBefore(args[i], "=");
			String value = StringUtils.substringAfter(args[i], "=");
			if(key_temp.equals(key))
				return value;
		}
		return "";
	}
	
	static public String varMap2Str(HashMap<String,Object> varMap, File templateFile) {
		VelocityEngine ve = new VelocityEngine();
		ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templateFile.getParent());
		ve.init();

		VelocityContext context = new VelocityContext();
		Iterator<String> keys=varMap.keySet().iterator();
		while(keys.hasNext()){
			String key=keys.next();
			context.put(key, varMap.get(key));
		}
		
		Template template =  ve.getTemplate(templateFile.getName(), "UTF-8");
		StringWriter writer = new StringWriter();
		if (template != null)
			template.merge(context, writer);

		writer.flush();
		return writer.toString();
	}
	
	static public List<String> trimLines(String text){
		String[] lines=StringUtils.split(text,"\n");
		List<String> lineList=new ArrayList<String> ();
		for(String line:lines){
			line=line.trim();
			if(!line.equals("")){
				lineList.add(line);
			}
			
		}
		return lineList;
	}
}
